package com.party.course.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.SQLOutput;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.date.DateUtil;
import com.party.business.domain.TOrder;
import com.party.business.mapper.TOrderMapper;
import com.party.common.constant.Constants;
import com.party.common.core.domain.AjaxResult;
import com.party.common.core.domain.entity.SysRole;
import com.party.common.core.domain.entity.SysUser;
import com.party.common.exception.ServiceException;
import com.party.common.exception.job.TaskException;
import com.party.common.utils.PageUtils;
import com.party.common.utils.SecurityUtils;
import com.party.common.utils.StringUtils;
import com.party.common.utils.WxUtils;
import com.party.course.domain.*;
import com.party.course.eumn.SubAmount;
import com.party.course.mapper.*;
import com.party.course.service.*;
import com.party.course.util.ReceiverModel;
import com.party.course.util.XunpayUtil;
import com.party.quartz.domain.SysJob;
import com.party.quartz.service.ISysJobService;
import com.party.quartz.util.CronUtils;
import com.party.quartz.util.ScheduleUtils;
import com.party.system.mapper.SysRoleMapper;
import com.party.system.mapper.SysUserMapper;
import com.party.system.service.impl.SysLogininforServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.hutool.core.util.IdUtil;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import static com.party.common.core.domain.AjaxResult.error;
import static com.party.course.util.XunpayUtil.convertYuanToCent;

/**
 * 排课信息Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
public class PlanClassServiceImpl extends ServiceImpl<PlanClassMapper, PlanClass> implements IplanClassService {
    @Resource
    private PlanClassMapper planClassMapper;
    @Resource
    private CoachInfoMapper coachInfoMapper;
    @Resource
    private StudentInfoMapper studentInfoMapper;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private ISubAmountInfoService subAmountInfoService;
    @Resource
    private IAmountInfoService amountInfoService;
    @Resource
    private IStudentChangeInfoService studentChangeInfoService;
    @Resource
    private TOrderMapper orderMapper;
    @Resource
    private IPayReqInfoService payReqInfoService;
    @Resource
    private SysLogininforServiceImpl sysLogininforService;
    @Resource
    private ISysJobService jobService;

    /**
     * 查询排课信息
     *
     * @param id 排课信息主键
     * @return 排课信息
     */
    @Override
    public PlanClass view(String id) {
        return planClassMapper.selectplanClassById(id);
    }

    /**
     * 查询排课信息列表
     *
     * @param planClass 排课信息
     * @return 排课信息
     */
    @Override
    public List<PlanClass> findList(PlanClass planClass) {
//        if(planClass.getOffFormal().equals("1")){
//            planClass.setDxk("99999");
//            planClass.setOffFormal("");
//        }
        Long userId = SecurityUtils.getUserId();
//        String roleId = planClass.getRoleId();
        String roleId = sysLogininforService.findLoginRoleId(userId.toString());
        //用于小程序查询列表
        if (StrUtil.isNotEmpty(planClass.getIsCoach())) {
            CoachInfo coachInfo = coachInfoMapper.findByUserId(userId.toString());
            if (ObjectUtil.isEmpty(coachInfo)) {
                return null;
            }
            if ("0".equals(planClass.getIsCoach())) {
                planClass.setCoaId(coachInfo.getId());
            } else if ("1".equals(planClass.getIsCoach())) {
                planClass.setLeaId(coachInfo.getId());
            }
        }
        if (StrUtil.isNotEmpty(roleId)) {
            SysRole role = sysRoleMapper.selectRoleById(Long.parseLong(roleId));
            CoachInfo coachInfo = coachInfoMapper.findByUserId(userId.toString());
            if ("交付中心".equals(role.getRoleName())) {
                planClass.setPayCenterId(userId.toString());
            } else if ("教练".equals(role.getRoleName())) {
                planClass.setCoaId(coachInfo.getId());
            } else if ("交付小组组长".equals(role.getRoleName())) {
                planClass.setPayGroupId(coachInfo.getPayGroupId());
            } else if ("学管师".equals(role.getRoleName())) {
                planClass.setLeaId(coachInfo.getId());
            }
        }
        //查询是否过期课程列表
        List<PlanClass> endList = new ArrayList<>();
        //查询是否反馈的课程列表
        List<PlanClass> feedbackList = new ArrayList<>();
        PageUtils.startPage();
        List<PlanClass> list = planClassMapper.selectplanClassList(planClass);
        for (PlanClass aClass : list) {
            if (StringUtils.isNotEmpty(aClass.getClassTime()) && StringUtils.isNotEmpty(aClass.getStarTime()) && StringUtils.isNotEmpty(aClass.getEndTime())) {
                String upClassTime = aClass.getClassTime() + " " + aClass.getStarTime() + "~" + aClass.getEndTime();
                aClass.setUpClassTime(upClassTime);
                //判断是否过期
                if (StrUtil.isNotEmpty(planClass.getIsExpired())) {
                    String endDate = aClass.getClassTime() + " " + aClass.getEndTime();
                    if ("0".equals(planClass.getIsExpired())) {
                        if (DateUtil.compare(DateUtil.parse(endDate), DateUtil.date()) < 0) {
                            endList.add(aClass);
                        }
                    } else {
                        if (DateUtil.compare(DateUtil.parse(endDate), DateUtil.date()) > 0) {
                            endList.add(aClass);
                        }
                    }

                }
            }
            //判断是否需要反馈
            if (StrUtil.isNotEmpty(planClass.getIsFeedback())) {
                if ("0".equals(planClass.getIsFeedback())) {
                    if (StrUtil.isNotEmpty(aClass.getLearnRemark())) {
                        feedbackList.add(aClass);
                    }
                } else {
                    if (StrUtil.isEmpty(aClass.getLearnRemark())) {
                        feedbackList.add(aClass);
                    }
                }
            }
        }
        if (StrUtil.isNotEmpty(planClass.getIsExpired())) {
            return endList;
        } else if (StrUtil.isNotEmpty(planClass.getIsFeedback())) {
            return feedbackList;
        } else {
            return list;
        }
    }


    @Override
    public int offClass(String id, String tupe) {
        PlanClass planClass = planClassMapper.selectplanClassById(id);
        if ("0".equals(tupe)) {
            //正式课
            planClass.setOffFormal("0");
        } else {
            //复习课
            planClass.setOffTest("0");
        }
        return planClassMapper.updateById(planClass);
    }

    /**
     * 新增排课信息
     *
     * @param planClass 排课信息
     * @return 结果
     */
    @Override
    @Transactional
    public int add(PlanClass planClass) {
        planClass.setId(IdUtil.simpleUUID());
        planClass.setDelFlag("0");
        planClass.setClassStatus("1");
        planClass.setOffFormal("1");
        planClass.setOffTest("1");
        planClass.setCreateTime(DateUtil.date());
        //判断是否是正式课或试课 并设置工资
//        if (StrUtil.isNotEmpty(planClass.getOrderType())) {
//            WageInfo wageInfo = null;
//            if ("1".equals(planClass.getOrderType())) {
//                //正式课
//                wageInfo = wageInfoMapper.findByType("1");
//            } else {
//                //试课
//                wageInfo = wageInfoMapper.findByType("0");
//            }
//            if (ObjectUtil.isNotEmpty(wageInfo)) {
//                planClass.setSalary(wageInfo.getBaseWage());
//                planClass.setPerSalary(wageInfo.getPerWage());
//            } else {
//                throw new RuntimeException("当前平台未设置工资，请先联系管理员设置工资！");
//            }
//        }
        if (StrUtil.isNotEmpty(planClass.getCoaId())) {
            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(planClass.getCoaId());
            if (ObjectUtil.isNotEmpty(coachInfo)) {
                SysUser user = sysUserMapper.selectUserById(Long.parseLong(coachInfo.getCreateBy()));
                planClass.setPayCenterId(coachInfo.getCreateBy());
                planClass.setPayCenterName(user.getUserName());
            }
        }
        if (StrUtil.isNotEmpty(planClass.getStuId())) {
            StudentInfo studentInfo = studentInfoMapper.selectStudentInfoById(planClass.getStuId());
            if (ObjectUtil.isNotEmpty(studentInfo)) {
                int learnNum = Integer.parseInt(planClass.getLearnNum());
                int surTime = Integer.parseInt(studentInfo.getSurplusLearnTime());
                if (learnNum > surTime) {
                    throw new RuntimeException("剩余课时不足，请先联系管理员！");
                }
                surTime=surTime-1;
                if (StringUtils.isEmpty(studentInfo.getFirstTime())) {
                    studentInfo.setFirstTime(planClass.getClassTime() + " " + planClass.getStarTime() + "~" + planClass.getEndTime());
                }
                studentInfo.setSurplusLearnTime(surTime+"");
                studentInfoMapper.updateById(studentInfo);
            }
            //查询并设置教师分账工资
            if (StrUtil.isNotEmpty(planClass.getOrderType())) {
                if ("1".equals(planClass.getOrderType())) {
                    BigDecimal learnNum = new BigDecimal(planClass.getLearnNum());
                    //正式课
                    BigDecimal amount = SubAmount.getAmountByCondition(Integer.parseInt(studentInfo.getTeachSection()), Integer.parseInt(studentInfo.getClassLevel()), 1, 1).multiply(learnNum);
                    planClass.setSalary(amount);
                    BigDecimal perAmount = SubAmount.getAmountByCondition(Integer.parseInt(studentInfo.getTeachSection()), Integer.parseInt(studentInfo.getClassLevel()), 1, 0).multiply(learnNum);
                    planClass.setPerSalary(perAmount);
                } else {
                    //试听课
                    planClass.setSalary(new BigDecimal(30));
                    planClass.setPerSalary(new BigDecimal(0));
                }
            }
        }
        //修改订单状态为 已排课
        TOrder order = orderMapper.findByOrderNo(planClass.getOrderCode());
        if (ObjectUtil.isNotEmpty(order) && StrUtil.isNotEmpty(order.getKcStatus()) && !"2".equals(order.getKcStatus())) {
            orderMapper.updateKcStatusByOrderNo(planClass.getOrderCode(), "2");
        }
        classNoticeTask(planClass);
        if("1".equals(planClass.getOrderType())){
            // 正式课才有这个
            List<ReceiverModel> list = new ArrayList<>();
            BigDecimal  unitAmount=BigDecimal.ZERO;
            //有合伙人，分账到合伙人账号
            if (StrUtil.isNotEmpty(planClass.getStoreUserId())) {
                PlanClass  planClassfist=new PlanClass();
                planClassfist.setStuId(planClass.getStuId());
                List<PlanClass> planClasses = planClassMapper.selectplanClassList(planClassfist);
                if(CollectionUtil.isEmpty(planClasses)){
                    StudentInfo studentInfo = studentInfoMapper.selectStudentInfoById(planClass.getStuId());
                    int section = Integer.parseInt(studentInfo.getTeachSection());
                    //课程等级：0一级，1二级
                    int level = Integer.parseInt(studentInfo.getClassLevel());
                    RealNameInfo realNameInfo_hhr = realNameInfoService.findByUserId(planClass.getStoreUserId() + "");
                    if (realNameInfo_hhr == null) {
                        throw new RuntimeException("合伙人请先签约，分账失败");
                    }
                    String applicationStatushhr = realNameInfo_hhr.getApplicationStatus();
                    if (!"COMPLETED".equals(applicationStatushhr)) {
                        throw new RuntimeException("合伙人请先签约完成，分账失败");
                    }
                    String merchantNohhr = realNameInfo_hhr.getMerchantNo();
                    //销售
                    BigDecimal learnNum = new BigDecimal(planClass.getLearnNum());

                    BigDecimal amountByCondition = SubAmount.getAmountByCondition(section, level, 3, 0);
                    System.out.println("mmmmmmmmmmmmmmmmmm"+amountByCondition);
                    unitAmount = amountByCondition.multiply(BigDecimal.valueOf(Long.valueOf(studentInfo.getBuyLearnTime())));
                    list.add(subAmountInfoService.add(SubAmountInfo.builder()
                            .orderCode(planClass.getOrderCode())
                            .ledgerNo(merchantNohhr)
                            .userId(planClass.getStoreUserId())
                            .planClassId(planClass.getId())
                            .teachSection(section)
                            .classLevel(level)
                            .role("3")
                            .profitAmount(unitAmount)
                            .build()));
                }
                list = list.stream().filter(model -> Double.valueOf(model.getAmount())> 0).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty( list)){
                    List<ReceiverModel> listnew = new ArrayList<>();
                    for (ReceiverModel model : list) {
                        // 分给用户的
                        BigDecimal amont =  BigDecimal.valueOf(Double.valueOf(model.getAmount()));
                        BigDecimal fzje = amont.subtract(amont.multiply(BigDecimal.valueOf(0.006))).setScale(2, RoundingMode.HALF_UP);
                        listnew.add(ReceiverModel.builder()
                                .ledgerNo(model.getLedgerNo())
                                .amount(fzje.toString())
                                .build());
                    }
                    System.out.println("排课数据集合："+listnew);
                    PayReqInfo payReqInfo = XunpayUtil.execOrder(planClass.getOrderCode(), listnew);
                    payReqInfoService.add(payReqInfo);
                }
                SysUser userCoach = sysUserMapper.selectUserById(Long.valueOf(planClass.getStoreUserId()));

                BigDecimal unitAmountjs = unitAmount.subtract(unitAmount.multiply(BigDecimal.valueOf(0.006))).setScale(2, RoundingMode.HALF_UP);
                BigDecimal totalA1 = userCoach.getAmount().add(unitAmountjs);
                userCoach.setAmount(totalA1);
                sysUserMapper.updateUserAmount(userCoach);
                amountInfoService.add(AmountInfo.builder()
                        .userId(planClass.getStoreUserId())
                        .planClassId(planClass.getId())
                        .planClassName(planClass.getClassName())
                        .amount(totalA1)
                        .changeAmount(unitAmountjs)
                        .countType("0")
                        .wageType("2")
                        .changeDetails("分润金额")
                        .validTime(DateUtil.now())
                        .validStatus("1")
                        .build());
            }

        }

        int insert = planClassMapper.insert(planClass);
        // 保存明细
        return insert;
    }

    /**
     * 添加课前通知的定时任务
     *
     * @param planClass
     */
    public void classNoticeTask(PlanClass planClass) {
        try {
            //根据上课时间获取两小时前的时间
            String startTime = planClass.getClassTime() + " " + planClass.getStarTime();
            LocalDateTime targetTime = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            LocalDateTime newTime = targetTime.minusHours(2);
            String newTimeStr = newTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
//            System.out.println("减去2小时后的时间是: " + newTimeStr);
            //获取上课时间的两小时前的时间
            LocalDateTime dateTime = LocalDateTime.parse(newTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
            int year = dateTime.getYear();
            int month = dateTime.getMonthValue();
            int day = dateTime.getDayOfMonth();
            int hour = dateTime.getHour();
            int minute = dateTime.getMinute();
            // 生成cron表达式
            String cronExpression = String.format("0 %d %d %d %d ? %d",
                    minute, hour, day, month, year);
//            System.out.println("生成的cron表达式: " + cronExpression);
            SysJob job = SysJob.builder()
                    .jobName(planClass.getCoaName() + "-上课通知")
                    .jobGroup("CLASS_NOTICE")
                    .invokeTarget("com.party.course.controller.PlanClassController.classNotice(\"" + planClass.getId() + "\")")
                    .cronExpression(cronExpression)
                    .misfirePolicy("1")
                    .concurrent("1")
                    .status("0")
                    .build();
            if (!CronUtils.isValid(job.getCronExpression())) {
                throw new RuntimeException("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
            } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
                throw new RuntimeException("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
            } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
                throw new RuntimeException("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
            } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
                throw new RuntimeException("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
            } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
                throw new RuntimeException("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
            } else if (!ScheduleUtils.whiteList(job.getInvokeTarget())) {
                throw new RuntimeException("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
            }
            job.setCreateBy(SecurityUtils.getUsername());
            jobService.insertJob(job);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 上课前2小时通知老师
     *
     * @param id
     */
    @Override
    public void classNotice(String id) {
        //上课通知
        PlanClass planClass = planClassMapper.selectplanClassById(id);
        if (ObjectUtil.isEmpty(planClass)) {
            throw new RuntimeException("排课信息为空，上课通知发送失败，请先联系管理员！");
        }
        if (StrUtil.isNotEmpty(planClass.getStuId()) && StrUtil.isNotEmpty(planClass.getCoaId())) {
            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(planClass.getCoaId());
            if (ObjectUtil.isNotEmpty(coachInfo)) {
                StudentInfo studentInfo = studentInfoMapper.selectStudentInfoById(planClass.getStuId());
                studentInfo.setWxUserId(coachInfo.getWxUserId());
                String startTime = planClass.getClassTime() + " " + planClass.getStarTime();
                studentInfo.setUpClassTime(startTime);
                studentInfo.setCoachName(coachInfo.getName());
                WxUtils.sendTextMessage("1", studentInfo);
            } else {
                throw new RuntimeException("教师信息为空，上课通知发送失败，请先联系管理员！");
            }
        } else {
            throw new RuntimeException("学员信息或教师信息为空，上课通知发送失败，请先联系管理员！");
        }
    }

    /**
     * 查询排课信息
     *
     * @param planClass
     */
    public void setColumn(PlanClass planClass) {
        if (StrUtil.isNotEmpty(planClass.getId())) {
            PlanClass aClass = planClassMapper.selectplanClassById(planClass.getId());
            if (ObjectUtil.isNotEmpty(aClass)) {
                planClass.setOrderCode(aClass.getOrderCode());
                planClass.setStuId(aClass.getStuId());
                planClass.setStuCode(aClass.getStuCode());
                planClass.setStuName(aClass.getStuName());
                planClass.setStoreUserId(aClass.getStoreUserId());
                planClass.setStoreCode(aClass.getStoreCode());
                planClass.setStoreName(aClass.getStoreName());
                planClass.setOrderType(aClass.getOrderType());
                planClass.setLeaId(aClass.getLeaId());
                planClass.setLeaName(aClass.getLeaName());
                planClass.setCoaId(aClass.getCoaId());
                planClass.setCoaName(aClass.getCoaName());
                planClass.setPayCenterId(aClass.getPayCenterId());
                planClass.setPayCenterName(aClass.getPayCenterName());
                planClass.setPayGroupId(aClass.getPayGroupId());
                if (StrUtil.isEmpty(planClass.getLearnNum()) && StrUtil.isNotEmpty(aClass.getLearnNum())) {
                    planClass.setLearnNum(aClass.getLearnNum());
                }
                if (StrUtil.isNotEmpty(planClass.getOffFormal()) && StrUtil.isNotEmpty(aClass.getOffFormal()) && "0".equals(aClass.getOffFormal())) {
                    planClass.setOffFormal(aClass.getOffFormal());
                }
                if (StrUtil.isNotEmpty(planClass.getOffTest()) && StrUtil.isNotEmpty(aClass.getOffTest()) && "0".equals(aClass.getOffTest())) {
                    planClass.setOffTest(aClass.getOffTest());
                }
            }
        }
    }

    /**
     * 修改排课信息
     *
     * @param planClass 排课信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateEntity(PlanClass planClass) {
        if (StringUtils.isEmpty(planClass.getOffFormal())) {
            planClass.setOffFormal("1");
        }
        if (StringUtils.isEmpty(planClass.getOffTest())) {
            planClass.setOffTest("1");
        }
        //必要关联字段赋值
        setColumn(planClass);
        if (StrUtil.isNotEmpty(planClass.getStuId())) {
            StudentInfo studentInfo = studentInfoMapper.selectStudentInfoById(planClass.getStuId());
            if (ObjectUtil.isEmpty(studentInfo)) {
                return 1;
            }
            if (StrUtil.isNotEmpty(planClass.getCoaId())) {
                studentInfo.setCoachId(planClass.getCoaId());
            }
            //消课计算学时
            if ((StrUtil.isNotEmpty(planClass.getOffFormal()) && "0".equals(planClass.getOffFormal()))) {
                //计算交付学时
                String orderType = planClass.getOrderType();
                Boolean isFormal = false;
                if ("1".equals(orderType)) {
                    if ("0".equals(planClass.getOffTest())) {
                        //正式课,最后消复习课的时候再计算学时
                        isFormal = true;
                    }
                } else {
                    isFormal = true;
                }
                if (isFormal) {
                    int payTime = Integer.parseInt(studentInfo.getPayLearnTime());
                    int learnNum = Integer.parseInt(planClass.getLearnNum());
                    int totalPayTime = payTime + learnNum;
                    studentInfo.setPayLearnTime(totalPayTime + "");
                    //计算剩余学时
                    int buyTime = Integer.parseInt(studentInfo.getBuyLearnTime());
                    int supTime = buyTime - totalPayTime;
                    studentInfo.setSurplusLearnTime(supTime + "");
                    //课时到期通知
                    if (supTime <= 2) {
                        if (StrUtil.isNotEmpty(studentInfo.getLearnId())) {
                            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(studentInfo.getLearnId());
                            if (ObjectUtil.isEmpty(coachInfo)) {
                                throw new RuntimeException("教师信息为空，上课通知发送失败，请先联系管理员！");
                            }
                            studentInfo.setWxUserId(coachInfo.getWxUserId());
                            studentInfo.setCoachName(coachInfo.getName());
                            String startTime = planClass.getClassTime() + " " + planClass.getStarTime();
                            studentInfo.setUpClassTime(startTime);
                            boolean sent = WxUtils.sendTextMessage("0", studentInfo);
                            if (!sent) {
                                throw new RuntimeException("学员课时到期通知发送失败");
                            }
                        } else {
                            throw new RuntimeException("教师信息为空，上课通知发送失败，请先联系管理员！");
                        }
                    }
                    //消课并修改为已上课状态
                    planClass.setClassStatus("0");
                    if (supTime == 0) {
                        //剩余学时为0，修改订单状态为已上课
                        orderMapper.updateKcStatusByOrderNo(planClass.getOrderCode(), "3");
                    }
                }

            }
            if (StringUtils.isNotEmpty(studentInfo.getCoachOrderStatus()) && "0".equals(studentInfo.getCoachOrderStatus())) {
                studentInfo.setCoachOrderStatus("1");
            }
            studentInfoMapper.updateById(studentInfo);
        }
        //消课分账
        subAmont(planClass);
        //消课打钱
        offClass(planClass);
        planClass.setUpdateTime(DateUtil.date());
        return planClassMapper.updateById(planClass);
    }


    /**
     * 修改排课信息
     *
     * @param planClass 排课信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateEntityFk(PlanClass planClass) {
        PlanClass planClass1 = planClassMapper.selectplanClassById(planClass.getId());
        planClass1.setLearnRemark(planClass.getLearnRemark());
        planClass1.setLearnPdf(planClass.getLearnPdf());
        return planClassMapper.updateById(planClass1);
    }

    @Transactional
    public int updateEntityKjx(PlanClass planClass) {
        String id = planClass.getId();

        // 扣款金额
        BigDecimal amount = planClass.getChangeAmount();
        if(amount==null){
            throw new ServiceException("请输入正确的金额");
        }
        if(amount.compareTo(BigDecimal.ZERO)<=0){
            throw new ServiceException("请输入正确的金额");
        }
        String changeDetails = planClass.getChangeDetails();
        QueryWrapper<AmountInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("plan_class_id", id);
        queryWrapper.eq("wage_type", "1");
        List<AmountInfo> list = amountInfoService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            AmountInfo amountInfo = list.get(0);
            String validStatus = amountInfo.getValidStatus();
            BigDecimal changeAmount = amountInfo.getChangeAmount();
            String changeDetails1 = amountInfo.getChangeDetails();
            if ("0".equals(validStatus)) {
                if (amount.compareTo(changeAmount) > 0) {
                    throw new ServiceException("请输入正确的金额");
                }
                amountInfo.setChangeAmount(amountInfo.getChangeAmount().subtract(amount));
                amountInfo.setChangeDetails(changeDetails1 + "==测试==" + changeDetails);
                amountInfoService.updateById(amountInfo);
                String userId = amountInfo.getUserId();
                SysUser user = sysUserMapper.selectUserById(Long.valueOf(userId));
                if (ObjectUtil.isEmpty(user)) {
                    throw new ServiceException("获取用户信息失败");
                }
                user.setAmount(user.getAmount().subtract(amount));
                sysUserMapper.updateUser(user);

            } else {
                throw new ServiceException("该排课已分账");
            }
        } else {
            throw new ServiceException("获取绩效金额失败");
        }

        return 1;


    }

    @Autowired
    private IRealNameInfoService realNameInfoService;

    /**
     * todo 测试阶段 仅对老师角色进行分账
     *
     * @param planClass
     */
    @Transactional
    public void subAmont1(PlanClass planClass) {
        log.warn("分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦分账啦");
        log.warn(planClass.toString());
        if (StrUtil.isNotEmpty(planClass.getCoaId()) && (StrUtil.isNotEmpty(planClass.getOffFormal()) && "0".equals(planClass.getOffFormal())) && (StrUtil.isNotEmpty(planClass.getOffTest()) && "0".equals(planClass.getOffTest()))) {
            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(planClass.getCoaId());
            if (ObjectUtil.isNotEmpty(coachInfo)) {
                planClass.setCoaName(coachInfo.getName());
                SysUser user = sysUserMapper.selectUserById(Long.parseLong(coachInfo.getCreateBy()));
                planClass.setPayCenterId(user.getUserId().toString());
                planClass.setPayCenterName(user.getUserName());
                //20250807 zhaoyongke 补充 查询教练的 商户号
                RealNameInfo realNameInfo = realNameInfoService.findByUserId(coachInfo.getUserId());
                if (realNameInfo == null) {
                    throw new RuntimeException("商户号为空，分账失败");
                }

                //排课标记分账
                if (StrUtil.isNotEmpty(coachInfo.getLedgerNo()) && StrUtil.isNotEmpty(planClass.getOrderCode())) {
                    //todo 接单分账 测试阶段只有一个账号只对教练进行分账
//                    List<ReceiverModel> models = subAmont(planClass);
                    List<ReceiverModel> list = new ArrayList<>();
                    BigDecimal learnNum = new BigDecimal(planClass.getLearnNum());
                    StudentInfo studentInfo = studentInfoMapper.selectStudentInfoById(planClass.getStuId());
                    if (ObjectUtil.isNotEmpty(studentInfo)) {
                        int section = Integer.parseInt(studentInfo.getTeachSection());
                        int level = Integer.parseInt(studentInfo.getClassLevel());
                        if ("0".equals(planClass.getOrderType())) {
                            //试听课  教练-30
                            list.add(subAmountInfoService.add(SubAmountInfo.builder()
                                    .orderCode(planClass.getOrderCode())
                                    .ledgerNo(coachInfo.getLedgerNo())
                                    .userId(coachInfo.getUserId())
                                    .planClassId(planClass.getId())
                                    .teachSection(section)
                                    .classLevel(level)
                                    .role("1")
                                    .profitAmount(new BigDecimal(30).multiply(learnNum))
                                    .build()));
                        } else {
                            //正式课
                            list.add(subAmountInfoService.add(SubAmountInfo.builder()
                                    .orderCode(planClass.getOrderCode())
                                    .ledgerNo(coachInfo.getLedgerNo())
                                    .userId(coachInfo.getUserId())
                                    .planClassId(planClass.getId())
                                    .teachSection(section)
                                    .classLevel(level)
                                    .role("1")
                                    .profitAmount(SubAmount.getAmountByCondition(section, level, 1, 1).multiply(learnNum))
                                    .build()));
                            //复习课
                            subAmountInfoService.add(SubAmountInfo.builder()
                                    .orderCode(planClass.getOrderCode())
                                    .ledgerNo(coachInfo.getLedgerNo())
                                    .userId(coachInfo.getUserId())
                                    .planClassId(planClass.getId())
                                    .teachSection(section)
                                    .classLevel(level)
                                    .role("1")
                                    .profitAmount(SubAmount.getAmountByCondition(section, level, 1, 0).multiply(learnNum))
                                    .build());
                        }
                    }
                    //调用三方分账，进行标记分账
//                    list.add(ReceiverModel.builder().ledgerNo(coachInfo.getLedgerNo()).amount("1").build());
                    list = list.stream().filter(model -> Double.valueOf(model.getAmount())> 0).collect(Collectors.toList());
                    if(CollectionUtil.isNotEmpty( list)){
                        PayReqInfo payReqInfo = XunpayUtil.execOrder(planClass.getOrderCode(), list);
                        payReqInfoService.add(payReqInfo);
                    }

                }
            }
        }
    }

    /**
     * 教练接单后 进行消课的分账逻辑实现
     *
     subAmont     * @param planClass
     */
    @Transactional
    public List<ReceiverModel> subAmont(PlanClass planClass) {
        List<ReceiverModel> list = new ArrayList<>();
        String merchantNoCom = "";

        BigDecimal unitAmount=new BigDecimal(0);
        Boolean hasHhr=false;
        int section=0;
        int level=0;
        Boolean  isZs=false;
        //生成分账数据
        if (StrUtil.isNotEmpty(planClass.getStuId())) {
            BigDecimal learnNum = new BigDecimal(planClass.getLearnNum());
            StudentInfo studentInfo = studentInfoMapper.selectStudentInfoById(planClass.getStuId());
            if (ObjectUtil.isNotEmpty(studentInfo) && ObjectUtil.isNotEmpty(planClass.getOrderType()) && StrUtil.isNotEmpty(planClass.getCoaId())) {

                //：0小学，1初中，2高中
                 section = Integer.parseInt(studentInfo.getTeachSection());
                //课程等级：0一级，1二级
                 level = Integer.parseInt(studentInfo.getClassLevel());
                //新建分账数据
                SubAmountInfo amountInfo = new SubAmountInfo();
                amountInfo.setPlanClassId(planClass.getId());
                amountInfo.setTeachSection(section);
                amountInfo.setClassLevel(level);
//                amountInfo.setCreateTime(DateUtil.date());
                CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(planClass.getCoaId());
                CoachInfo leaCoach = coachInfoMapper.selectCoachInfoById(planClass.getLeaId());
                if ("0".equals(planClass.getOrderType())) {
                    //试听课分账
                    //交付中心9.9
                    //2005 0807  zhaoyongke 要改成 给公司分账
                    SysUser comUser = sysUserMapper.selectUserByUserName("公司");
                    RealNameInfo realNameInfo = realNameInfoService.findByUserId(comUser.getUserId() + "");
                    if (realNameInfo == null) {
                        throw new RuntimeException("公司请先签约，分账失败");
                    }
                    String applicationStatus = realNameInfo.getApplicationStatus();
                    if (!"COMPLETED".equals(applicationStatus)) {
                        throw new RuntimeException("公司请先签约完成，分账失败");
                    }
                    String merchantNo = realNameInfo.getMerchantNo();
                    merchantNoCom=merchantNo;
                    list.add(subAmountInfoService.add(SubAmountInfo.builder()
                            .orderCode(planClass.getOrderCode())
                            .ledgerNo(merchantNo)
                            .userId(comUser.getUserId() + "")
                            .planClassId(planClass.getId())
                            .teachSection(section)
                            .classLevel(level)
                            .role("0")
                            .profitAmount(new BigDecimal("9.9").multiply(learnNum))
                            .build()));
                    //
                    //教练-30

                    RealNameInfo realNameInfojl = realNameInfoService.findByUserId(coachInfo.getUserId() + "");
                    if (realNameInfojl == null) {
                        throw new RuntimeException("教练请先签约，分账失败");
                    }
                    String applicationStatusjl = realNameInfojl.getApplicationStatus();
                    if (!"COMPLETED".equals(applicationStatusjl)) {
                        throw new RuntimeException("教练请先签约完成，分账失败");
                    }
                    String merchantNojl = realNameInfojl.getMerchantNo();
                    list.add(subAmountInfoService.add(SubAmountInfo.builder()
                            .orderCode(planClass.getOrderCode())
                            .ledgerNo(merchantNojl)
                            .userId(coachInfo.getUserId())
                            .planClassId(planClass.getId())
                            .teachSection(section)
                            .classLevel(level)
                            .role("1")
                            .profitAmount(new BigDecimal("30").multiply(learnNum))
                            .build()));
                } else {
                    if ("0".equals(planClass.getOffFormal()) && !"0".equals(planClass.getOffTest())) {
                        isZs=true;
                        //正式课分账
                        //0交付中心-教练的创建人
                        if (ObjectUtil.isNotEmpty(coachInfo)) {
                            RealNameInfo realNameInfocreateBy = realNameInfoService.findByUserId(coachInfo.getCreateBy() + "");
                            if (realNameInfocreateBy == null) {
                                throw new RuntimeException("交付中心请先签约，分账失败");
                            }
                            String applicationStatus = realNameInfocreateBy.getApplicationStatus();
                            if (!"COMPLETED".equals(applicationStatus)) {
                                throw new RuntimeException("交付中心，请先签约完成，分账失败");
                            }
                            String merchantNocreateBy = realNameInfocreateBy.getMerchantNo();
                            list.add(subAmountInfoService.add(SubAmountInfo.builder()
                                    .orderCode(planClass.getOrderCode())
                                    .ledgerNo(merchantNocreateBy)
                                    .userId(coachInfo.getCreateBy())
                                    .planClassId(planClass.getId())
                                    .teachSection(section)
                                    .classLevel(level)
                                    .role("0")
                                    .profitAmount(SubAmount.getAmountByCondition(section, level, 0, 1).multiply(learnNum))
                                    .build()));
                        }
                        SysUser comUser = sysUserMapper.selectUserByUserName("公司");

                        if (ObjectUtil.isNotEmpty(comUser)) {
                            RealNameInfo realNameInfo_com = realNameInfoService.findByUserId(comUser.getUserId() + "");
                            if (realNameInfo_com == null) {
                                throw new RuntimeException("公司请先签约，分账失败");
                            }
                            String applicationStatus = realNameInfo_com.getApplicationStatus();
                            if (!"COMPLETED".equals(applicationStatus)) {
                                throw new RuntimeException("公司请先签约完成，分账失败");
                            }
                            merchantNoCom = realNameInfo_com.getMerchantNo();
                            //公司
                            BigDecimal amount1 = SubAmount.getAmountByCondition(section, level, 5, 1).multiply(learnNum);
                            list.add(subAmountInfoService.add(SubAmountInfo.builder()
                                    .orderCode(planClass.getOrderCode())
                                    .ledgerNo(merchantNoCom)
                                    .userId(comUser.getUserId().toString())
                                    .planClassId(planClass.getId())
                                    .teachSection(section)
                                    .classLevel(level)
                                    .role("5")
                                    .profitAmount(amount1)
                                    .build()));

                        }
                        //交付小组组长
                        String payGroupId = planClass.getPayGroupId();
                        CoachInfo coachInfoquery = new CoachInfo();
                        coachInfoquery.setPayGroupId(payGroupId);
                        coachInfoquery.setRoleType("1");
                        List<CoachInfo> jfzzList = coachInfoMapper.selectCoachInfoList(coachInfoquery);
                        if (CollectionUtil.isNotEmpty(jfzzList)) {
                            String userId = jfzzList.get(0).getUserId();

                            RealNameInfo realNameInfo_zz = realNameInfoService.findByUserId(userId + "");
                            if (realNameInfo_zz == null) {
                                throw new RuntimeException("交付小组组长请先签约，分账失败");
                            }
                            String applicationStatus = realNameInfo_zz.getApplicationStatus();
                            if (!"COMPLETED".equals(applicationStatus)) {
                                throw new RuntimeException("交付小组组长请先签约完成，分账失败");
                            }
                            String merchantNoZ = realNameInfo_zz.getMerchantNo();

                            list.add(subAmountInfoService.add(SubAmountInfo.builder()
                                    .orderCode(planClass.getOrderCode())
                                    .ledgerNo(merchantNoZ)
                                    .userId(userId)
                                    .planClassId(planClass.getId())
                                    .teachSection(section)
                                    .classLevel(level)
                                    .role("6")
                                    .profitAmount(SubAmount.getAmountByCondition(section, level, 6, 1).multiply(learnNum))
                                    .build()));
                        }


                        RealNameInfo realNameInfo_caach = realNameInfoService.findByUserId(coachInfo.getUserId() + "");
                        if (realNameInfo_caach == null) {
                            throw new RuntimeException("教练请先签约，分账失败");
                        }
                        String applicationStatus = realNameInfo_caach.getApplicationStatus();
                        if (!"COMPLETED".equals(applicationStatus)) {
                            throw new RuntimeException("教练请先签约完成，分账失败");
                        }
                        String merchantNo_caach = realNameInfo_caach.getMerchantNo();
                        //1教练
                        //正式课
                        list.add(subAmountInfoService.add(SubAmountInfo.builder()
                                .orderCode(planClass.getOrderCode())
                                .ledgerNo(merchantNo_caach)
                                .userId(coachInfo.getUserId())
                                .planClassId(planClass.getId())
                                .teachSection(section)
                                .classLevel(level)
                                .role("1")
                                .profitAmount(SubAmount.getAmountByCondition(section, level, 1, 1).multiply(learnNum))
                                .build()));
                        //复习课
                        list.add(subAmountInfoService.add(SubAmountInfo.builder()
                                .orderCode(planClass.getOrderCode())
                                .ledgerNo(merchantNo_caach)
                                .userId(coachInfo.getUserId())
                                .planClassId(planClass.getId())
                                .teachSection(section)
                                .classLevel(level)
                                .role("1")
                                .profitAmount(SubAmount.getAmountByCondition(section, level, 1, 0).multiply(learnNum))
                                .build()));


                        //todo 4软件(固定账号)
                        SysUser appUser = sysUserMapper.selectUserByUserName("软件");
                        if (ObjectUtil.isNotEmpty(appUser)) {

                            RealNameInfo realNameInfo_rj = realNameInfoService.findByUserId(appUser.getUserId() + "");
                            if (realNameInfo_rj == null) {
                                throw new RuntimeException("软件请先签约，分账失败");
                            }
                            String applicationStatusrj = realNameInfo_rj.getApplicationStatus();
                            if (!"COMPLETED".equals(applicationStatusrj)) {
                                throw new RuntimeException("软件请先签约完成，分账失败");
                            }
                            String merchantNorj = realNameInfo_rj.getMerchantNo();
                            list.add(subAmountInfoService.add(SubAmountInfo.builder()
                                    .orderCode(planClass.getOrderCode())
                                    .ledgerNo(merchantNorj)
                                    .userId(appUser.getUserId().toString())
                                    .planClassId(planClass.getId())
                                    .teachSection(section)
                                    .classLevel(level)
                                    .role("4")
                                    .profitAmount(SubAmount.getAmountByCondition(section, level, 4, 1).multiply(learnNum))
                                    .build()));
                        }
                        //3合伙人
                        //销售-无合伙人
                        BigDecimal notUnitMan = new BigDecimal(0);
                        //非销售-无合伙人
                        BigDecimal notUnitManSales = new BigDecimal(0);
                        //销售-有合伙人
                         unitAmount = SubAmount.getAmountByCondition(section, level, 3, 0).multiply(learnNum);
                        //非销售-有合伙人
                        // BigDecimal unitAmountSales = SubAmount.getAmountByCondition(section, level, 3, 1).multiply(learnNum);
                        if (StrUtil.isNotEmpty(planClass.getStoreUserId())) {
                            hasHhr=true;
                            //有合伙人，分账到合伙人账号
//                            RealNameInfo realNameInfo_hhr = realNameInfoService.findByUserId(planClass.getStoreUserId()+"");
//                            if(realNameInfo_hhr==null){
//                                throw new RuntimeException("合伙人请先签约，分账失败");
//                            }
//                            String applicationStatushhr = realNameInfo_hhr.getApplicationStatus();
//                            if(!"COMPLETED".equals(applicationStatushhr)){
//                                throw new RuntimeException("合伙人请先签约完成，分账失败");
//                            }
//                            String merchantNohhr = realNameInfo_hhr.getMerchantNo();
//                            //销售
//                            list.add(subAmountInfoService.add(SubAmountInfo.builder()
//                                    .orderCode(planClass.getOrderCode())
//                                    .ledgerNo(merchantNohhr)
//                                    .userId(planClass.getStoreUserId())
//                                    .planClassId(planClass.getId())
//                                    .teachSection(section)
//                                    .classLevel(level)
//                                    .role("3")
//                                    .profitAmount(unitAmount)
//                                    .build()));

                            //  合伙人上级 俱乐部
                            SysUser user = sysUserMapper.selectUserById(Long.parseLong(planClass.getStoreUserId()));
                            String createBy = user.getCreateBy();
                            RealNameInfo realNameInfo_jlb = realNameInfoService.findByUserId(createBy + "");
                            if (realNameInfo_jlb == null) {
                                throw new RuntimeException("合伙人上级俱乐部请先签约，分账失败");
                            }
                            String applicationStatujlb = realNameInfo_jlb.getApplicationStatus();
                            if (!"COMPLETED".equals(applicationStatujlb)) {
                                throw new RuntimeException("合伙人上级俱乐部请先签约完成，分账失败");
                            }
                            String merchantNoJLB = realNameInfo_jlb.getMerchantNo();
                            BigDecimal unitAmountJLB = SubAmount.getAmountByCondition(section, level, 7, 1);
                            list.add(subAmountInfoService.add(SubAmountInfo.builder()
                                    .orderCode(planClass.getOrderCode())
                                    .ledgerNo(merchantNoJLB)
                                    .userId(createBy)
                                    .planClassId(planClass.getId())
                                    .teachSection(section)
                                    .classLevel(level)
                                    .role("7")
                                    .profitAmount(unitAmountJLB)
                                    .build()));
                        } else {
                            //无合伙人，分账到公司
                            //销售
                            notUnitMan = notUnitMan.add(unitAmount).add(BigDecimal.valueOf(5));
//                            //非销售
//                            notUnitManSales = notUnitMan.add(unitAmountSales);
                        }
                        //todo 5公司(固定账号)
                        SysUser comUser11 = sysUserMapper.selectUserByUserName("公司");
                        if (ObjectUtil.isNotEmpty(comUser)) {
                            //销售 没用
                            BigDecimal amount1 = SubAmount.getAmountByCondition(section, level, 5, 0).multiply(learnNum);
                            BigDecimal  ss=amount1.add(notUnitMan);
                            if(ss.compareTo(BigDecimal.ZERO)>0){
                                list.add(subAmountInfoService.add(SubAmountInfo.builder()
                                        .orderCode(planClass.getOrderCode())
                                        .ledgerNo(merchantNoCom)
                                        .userId(comUser11.getUserId().toString())
                                        .planClassId(planClass.getId())
                                        .teachSection(section)
                                        .classLevel(level)
                                        .role("5")
                                        .profitAmount(amount1.add(notUnitMan))
                                        .build()));
                            }
                        }
                    }

                }
            }
        }
        list = list.stream().filter(model -> Double.valueOf(model.getAmount())> 0).collect(Collectors.toList());
        if(CollectionUtil.isNotEmpty( list)){
            List<ReceiverModel> listnew = new ArrayList<>();
            BigDecimal  totalUsercom=BigDecimal.ZERO;
            for (ReceiverModel model : list) {
                // 分给用户的
                BigDecimal amont = new BigDecimal(model.getAmount());
                BigDecimal fzje = amont.subtract(amont.multiply(BigDecimal.valueOf(0.006))).setScale(2, RoundingMode.HALF_UP);
                listnew.add(ReceiverModel.builder()
                        .ledgerNo(model.getLedgerNo())
                        .amount(fzje.toString())
                        .build());
                totalUsercom=totalUsercom.add(fzje);
            }
            BigDecimal hrhje=BigDecimal.ZERO;
            // 之前分给合伙人的
            if(hasHhr){
                 hrhje = unitAmount.subtract(unitAmount.multiply(BigDecimal.valueOf(0.006))).setScale(2, RoundingMode.HALF_UP);
            }
            BigDecimal totalamount =BigDecimal.ZERO;
            if(isZs){
                totalamount = SubAmount.getAmountByCondition(section, level, 9, 9);
            }else{
                // 试听课固定 39.9
                totalamount= new BigDecimal("39.9");
            }
            // 三方抽成
            BigDecimal sfamount = totalamount.multiply(new BigDecimal(0.0039)).setScale(2, RoundingMode.HALF_UP);
            BigDecimal comamuunt =BigDecimal.ZERO;
            if(isZs){
                // 计算公司的
                 comamuunt = totalamount.subtract(sfamount).subtract(hrhje).subtract(totalUsercom).setScale(2, RoundingMode.HALF_UP);;
            }else{
                // 不用去掉合伙人的
                comamuunt = totalamount.subtract(sfamount).subtract(totalUsercom).setScale(2, RoundingMode.HALF_UP);;
            }
            // 分给公司的
            listnew.add(ReceiverModel.builder().ledgerNo(merchantNoCom).amount(comamuunt.toString()).build());
            if(comamuunt.compareTo(BigDecimal.ZERO)>0){
                SysUser comUser = sysUserMapper.selectUserByUserName("公司");
                BigDecimal totalA2 = comUser.getAmount().add(comamuunt);
                comUser.setAmount(totalA2);
                sysUserMapper.updateUserAmount(comUser);
                // 插入明细
                amountInfoService.add(AmountInfo.builder()
                        .userId(comUser.getUserId()+"")
                        .planClassId(planClass.getId())
                        .planClassName(planClass.getClassName())
                        .amount(totalA2)
                        .changeAmount(comamuunt)
                        .countType("0")
                        .wageType("2")
                        .changeDetails("公司抽成")
                        .validTime(DateUtil.now())
                        .validStatus("1")
                        .build());
            }
            log.warn("总金额："+totalamount+"  公司抽成："+comamuunt+"   之前合伙人："+hrhje+"   用户总分成："+totalUsercom+"   三方抽成："+sfamount);
            System.out.println("数据集合："+listnew);
            PayReqInfo payReqInfo = XunpayUtil.execOrder(planClass.getOrderCode(), listnew);
            payReqInfoService.add(payReqInfo);
        }

        return list;
    }

    /**
     * 消课打钱
     *
     * @param planClass
     */
    @Transactional
    public void offClass(PlanClass planClass) {
        log.warn("消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱消课打钱");
        log.warn(planClass.toString());
        //消课-----打钱到账号余额
        Long userId = SecurityUtils.getUserId();
        SysUser userCoach = sysUserMapper.selectUserById(userId);
        //查询你教练名下的分账数据
        List<SubAmountInfo> subAmountInfos = subAmountInfoService.findByClassIdAndUid(planClass.getId(), userId.toString(), "1");
        if (StrUtil.isNotEmpty(planClass.getOffTest()) && "0".equals(planClass.getOffTest())) {
            //复习课-先只打钱给教练
            if (!subAmountInfos.isEmpty()) {
                //查找金额大的分账数据-复习课金额
                SubAmountInfo amountInfo = subAmountInfos.get(1);
                BigDecimal profitAmount = amountInfo.getProfitAmount();
                BigDecimal jlfcJe = profitAmount.subtract(profitAmount.multiply(BigDecimal.valueOf(0.006))).setScale(2, RoundingMode.HALF_UP);

                BigDecimal totalAmount = userCoach.getAmount().add(jlfcJe);
//                userCoach.setAmount(totalAmount);
//                sysUserMapper.updateUserAmount(userCoach);
                //绩效工资一天后才可以提现(88888888888888888)
                amountInfoService.add(AmountInfo.builder()
                        .userId(amountInfo.getUserId())
                        .planClassId(planClass.getId())
                        .planClassName(planClass.getClassName())
                        .amount(totalAmount)
                        .changeAmount(jlfcJe)
                        .countType("0")
                        .wageType("1")
                        .changeDetails("绩效8工资发放")
                        .validTime(String.valueOf(DateUtil.offsetDay(DateUtil.date(), 30)))
                        .validStatus("0")
                        .build());
            }
        }
        if (StrUtil.isNotEmpty(planClass.getOffFormal()) && "0".equals(planClass.getOffFormal())) {
            //正式课（正式课都会伴随一节复习课，而试听课没有）
            if (StrUtil.isNotEmpty(planClass.getOrderType())) {
                if ("0".equals(planClass.getOrderType())) {
                    //试听课-打钱给到教练和公司
                    //教练
                    BigDecimal  money30=new BigDecimal(30);
                    BigDecimal jlfcJe = money30.subtract(money30.multiply(BigDecimal.valueOf(0.006))).setScale(2, RoundingMode.HALF_UP);
                    BigDecimal totalA1 = userCoach.getAmount().add(jlfcJe);
                    userCoach.setAmount(totalA1);
                    sysUserMapper.updateUserAmount(userCoach);
                    amountInfoService.add(AmountInfo.builder()
                            .userId(userId.toString())
                            .planClassId(planClass.getId())
                            .planClassName(planClass.getClassName())
                            .amount(totalA1)
                            .changeAmount(jlfcJe)
                            .countType("0")
                            .wageType("0")
                            .changeDetails("试听课工资发放-")
                            .validTime(DateUtil.now())
                            .validStatus("1")
                            .build());


                    BigDecimal  moneycom9=new BigDecimal(9.9);
                    BigDecimal comJe = moneycom9.subtract(moneycom9.multiply(BigDecimal.valueOf(0.006))).setScale(2, RoundingMode.HALF_UP);
                    //公司
                    SysUser comUser = sysUserMapper.selectUserByUserName("公司");
//                    CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(planClass.getCoaId());
                    SysUser unitUser = sysUserMapper.selectUserById(comUser.getUserId());
                    BigDecimal totalA2 = unitUser.getAmount().add(comJe);
                    unitUser.setAmount(totalA2);
                    sysUserMapper.updateUserAmount(unitUser);
                    amountInfoService.add(AmountInfo.builder()
                            .userId(unitUser.getUserId() + "")
                            .planClassId(planClass.getId())
                            .planClassName(planClass.getClassName())
                            .amount(totalA2)
                            .changeAmount(comJe)
                            .countType("0")
                            .wageType("2")
                            .changeDetails("试听课分润金额")
                            .validTime(DateUtil.now())
                            .validStatus("1")
                            .build());
                } else {
                    //正式课

                    if ("0".equals(planClass.getOffFormal()) && !"0".equals(planClass.getOffTest())) {
                        //打钱给教练
                        if (!subAmountInfos.isEmpty()) {
                            //查找金额大的分账数据-正式课金额
                            SubAmountInfo amountInfo = subAmountInfos.get(0);
                            BigDecimal profitAmount = amountInfo.getProfitAmount();
                            BigDecimal profitAmount1 = profitAmount.subtract(profitAmount.multiply(BigDecimal.valueOf(0.006))).setScale(2, RoundingMode.HALF_UP);

                            BigDecimal totalAmount = userCoach.getAmount().add(profitAmount1);
                            userCoach.setAmount(totalAmount);
                            sysUserMapper.updateUserAmount(userCoach);
                            amountInfoService.add(AmountInfo.builder()
                                    .userId(amountInfo.getUserId())
                                    .planClassId(planClass.getId())
                                    .planClassName(planClass.getClassName())
                                    .amount(totalAmount)
                                    .changeAmount(profitAmount1)
                                    .countType("0")
                                    .wageType("0")
                                    .changeDetails("正式课工资发放-教练")
                                    .validTime(DateUtil.now())
                                    .validStatus("1")
                                    .build());
                        }

                        //打钱给非教练的其他人
                        List<SubAmountInfo> subAmountOthers = subAmountInfoService.findByClassIdAndNotUid(planClass.getId(), planClass.getCoaId(), "1");
                        if (!subAmountOthers.isEmpty()) {
                            for (SubAmountInfo amountInfo : subAmountOthers) {
                                // 原来是7 为什么改成3了？悬案？？？？庆瑞让改的20251014
                                if(!"3".equals(amountInfo.getRole())){
                                    SysUser user = sysUserMapper.selectUserById(Long.parseLong(amountInfo.getUserId()));
                                    BigDecimal profitAmount = amountInfo.getProfitAmount();
                                    BigDecimal profitAmount2 = profitAmount.subtract(profitAmount.multiply(BigDecimal.valueOf(0.006))).setScale(2, RoundingMode.HALF_UP);
                                    BigDecimal totalAmount = user.getAmount().add(profitAmount2);
                                    user.setAmount(totalAmount);
                                    sysUserMapper.updateUserAmount(user);
                                    amountInfoService.add(AmountInfo.builder()
                                            .userId(amountInfo.getUserId())
                                            .planClassId(planClass.getId())
                                            .planClassName(planClass.getClassName())
                                            .amount(totalAmount)
                                            .changeAmount(profitAmount2)
                                            .countType("0")
                                            .wageType("2")
                                            .changeDetails("正式课分润非教练的其他人")
                                            .validTime(DateUtil.now())
                                            .validStatus("1")
                                            .build());
                                }

                            }
                        }

                    }


                }
            }
            //消课 新增课程变动信息
            studentChangeInfoService.add(StudentChangeInfo.builder()
                    .planClassId(planClass.getId())
                    .orderCode(planClass.getOrderCode())
                    .stuId(planClass.getStuId())
                    .stuCode(planClass.getStuCode())
                    .stuName(planClass.getStuName())
                    .tyep("0")
                    .genre("1")
                    .changeTimeNum(planClass.getLearnNum())
                    .datil("学员上课，教练消课")
                    .build());
        }
    }

    /**
     * 批量删除排课信息
     *
     * @param ids 需要删除的排课信息主键
     * @return 结果
     */
    @Override
    public int deleteIds(List<String> ids) {
        for (String id : ids) {
            PlanClass pClass = planClassMapper.selectplanClassById(id);
            if ("0".equals(pClass.getClassStatus())) {
                throw new RuntimeException("当前" + pClass.getClassName() + "课程订单已接单或已正常上课，不可删除！");
            }
            //若是第一次排课 则置空首次上课时间
            StudentInfo studentInfo = studentInfoMapper.selectStudentInfoById(pClass.getStuId());
            if (ObjectUtil.isEmpty(studentInfo)) {
                studentInfoMapper.updateFirstTimeById(pClass.getStuId(), null);
            }
        }
        return planClassMapper.deleteplanClassByIds(ids);
    }

    /**
     * 删除排课信息信息
     *
     * @param id 排课信息主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return planClassMapper.deleteplanClassById(id);
    }
}
